// AdminServiceImpl.java
package com.lab.service.impl;

import com.lab.common.Result;
import com.lab.common.leavePageResult;
import com.lab.dto.LeaveApprovalDTO;
import com.lab.dto.LeaveRequestPageQueryDTO;
import com.lab.entity.LeaveRequest;
import com.lab.entity.Member;
import com.lab.mapper.LeaveRequestMapper;
import com.lab.mapper.MemberMapper;
import com.lab.service.LeaveRequestService;
import com.lab.vo.LeaveRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LeaveRequestServiceImpl implements LeaveRequestService {

    @Autowired
    private LeaveRequestMapper leaveRequestMapper;
    @Autowired
    private MemberMapper    memberMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result approve(LeaveApprovalDTO leaveApprovalDTO, Long adminId) {

        // 1. 查询请假申请是否存在
        LeaveRequest leaveRequest = leaveRequestMapper.selectById(leaveApprovalDTO.getLeaveId());
        if (leaveRequest == null) {
            log.warn("请假审批失败：申请记录不存在，leaveId={}", leaveApprovalDTO.getLeaveId());
            return Result.fail("请假申请不存在");
        }

        // 2. 校验申请状态（只能审批待审批状态）
        if (!"pending".equals(leaveRequest.getStatus())) {
            log.warn("请假审批失败：申请已处理，leaveId={}, 当前状态={}",
                    leaveApprovalDTO.getLeaveId(), leaveRequest.getStatus());
            return Result.fail("该申请已处理，无需重复操作");
        }

        // 3. 更新请假申请状态
        leaveRequest.setStatus(leaveApprovalDTO.getStatus());
        leaveRequest.setApproveBy(adminId.intValue()); // 转换为int（数据库字段为int）
        leaveRequest.setApproveTime(LocalDateTime.now());

        int rows = leaveRequestMapper.updateById(leaveRequest);
        log.info("更新请假申请ID: {}，影响行数: {}", leaveApprovalDTO.getLeaveId(), rows);

        if (rows > 0) {
            log.info("请假审批成功：leaveId={}, 审批状态={}, 审批人={}",
                    leaveApprovalDTO.getLeaveId(), leaveApprovalDTO.getStatus(), adminId);
            return Result.success("审批成功");
        } else {
            log.error("请假审批失败：数据库更新异常，leaveId={}", leaveApprovalDTO.getLeaveId());
            return Result.fail("审批失败，请重试");
        }
    }
    /**
     * 分页查询请假申请实现
     */
    @Override
    public leavePageResult<LeaveRequestVO> pageQuery(LeaveRequestPageQueryDTO queryDTO) {
        // 1. 计算分页参数
        int pageNum = queryDTO.getPageNum();
        int pageSize = queryDTO.getPageSize();
        int start = (pageNum - 1) * pageSize;

        // 2. 查询总记录数
        Long total = leaveRequestMapper.countByCondition(queryDTO);
        if (total == 0) {
            return leavePageResult.of(0L, List.of(), pageNum, pageSize);
        }

        // 3. 查询当前页数据（实体类列表）
        List<LeaveRequest> leaveRequests = leaveRequestMapper.pageQuery(queryDTO, start, pageSize);

        // 4. 转换为VO（关联查询申请人姓名）
        List<LeaveRequestVO> records = leaveRequests.stream().map(leaveRequest -> {
            LeaveRequestVO vo = new LeaveRequestVO();
            BeanUtils.copyProperties(leaveRequest, vo);

            // 补充申请人姓名（从member表查询）
            Member member = memberMapper.selectById(leaveRequest.getMemberId());
            if (member != null) {
                vo.setMemberName(member.getName());
            }

            return vo;
        }).collect(Collectors.toList());

        // 5. 封装分页结果
        return leavePageResult.of(total, records, pageNum, pageSize);
    }

}